ai<template>
  <div class="login">
    <h1>{{ isRegister ? '注册' : '登录' }}</h1>
    <form @submit.prevent="handleSubmit">
      <div>
        <label>账号:</label>
        <input v-model="username" type="text" required />
      </div>
      <div>
        <label>密码:</label>
        <input v-model="password" type="password" required />
      </div>
      <div v-if="isRegister">
        <label>确认密码:</label>
        <input v-model="confirmPassword" type="password" required />
      </div>
      <button type="submit">{{ isRegister ? '注册' : '登录' }}</button>
    </form>
    <button @click="isRegister = !isRegister" class="toggle-btn">
      {{ isRegister ? '已有账号？去登录' : '没有账号？去注册' }}
    </button>
     <!-- 滑块验证码组件 -->
    <SliderCaptcha
      ref="captchaRef" 
      @verifySuccess="onVerifySuccess" 
    />
  </div>
</template>

<script setup lang="ts">
// import SliderCaptcha from '~/components/SliderCaptcha.vue'

const isVerified = ref(false) // 验证状态
const username = ref('')
const password = ref('')
const confirmPassword = ref('')
const isRegister = ref(false)
const captchaRef = ref<any>(null)

const onVerifySuccess = () => {
  isVerified.value = true
  handleSubmit()
}

const handleSubmit = () => {
  // 验证验证码
  // 1. 先检查滑块验证是否通过
  if (!isVerified.value) {
    // 未验证则打开验证码弹窗
    captchaRef.value?.open()
    return
  }
  return isRegister.value ? handleRegister() : handleLogin()
}

const isLoading = ref(false)
const errorMessage = ref('')

const handleLogin = async () => {
  isLoading.value = true
  errorMessage.value = ''
  
  try {
// 由于 $fetch 返回值类型为 unknown，需要进行类型断言
const {data} = await $fetch<{ data: any }>('/api/login', {
      method: 'POST',
      body: {
        username: username.value,
        password: password.value
      }
    })
    console.log('登录响应:', data)
    // 登录成功后跳转
    navigateTo('/my-music')
    
    // 存储用户信息
    const user = useUserStore()
    user.setUser(data.user)
  } catch (error: any) {
    console.log('登录错误:', error.status)
    if (typeof error === 'object' && error !== null && 'data' in error) {
      const typedError = error as { data: { statusMessage?: string } };
      errorMessage.value = typedError.data?.statusMessage || '登录失败，请重试';
    } else if (error.status === 401) {
      errorMessage.value = '账号或密码错误';
    } else {
      errorMessage.value = '登录失败，请重试';
    }
    alert(errorMessage.value)
  } finally {
    isLoading.value = false
  }
}
const handleRegister = async () => {
  console.log('注册函数被调用')
  isLoading.value = true
  errorMessage.value = ''
  
  try {
    console.log('尝试注册:', username.value)
// 由于 $fetch 返回值类型为 unknown，需要进行类型断言
const { data } = await $fetch<{ data: any }>('/api/register', {
      method: 'POST',
      body: {
        username: username.value,
        password: password.value,
        confirmPassword: confirmPassword.value
      }
    })
    console.log('注册响应:', data)
    
    // 注册成功后自动登录
    await handleLogin()
    
  } catch (error) {
    console.error('注册错误:', error)
if (typeof error === 'object' && error !== null && 'data' in error) {
  const typedError = error as { data: { statusMessage?: string } };
  errorMessage.value = typedError.data?.statusMessage || '注册失败，请重试';
} else {
  errorMessage.value = '注册失败，请重试';
}
// 由于 error 类型为 unknown，需要先进行类型断言，假设 error 可能是包含 response 属性的对象
if (typeof error === 'object' && error !== null && 'response' in error) {
// 由于 error.response 类型为 unknown，需要进行类型断言
if (typeof error.response === 'object' && error.response !== null && '_data' in error.response) {
  const typedResponse = error.response as { _data: any };
  console.log('错误详情:', typedResponse._data);
}
    }
  } finally {
    isLoading.value = false
  }
}
definePageMeta({
  middleware: 'auth'
})
</script>

<style scoped>
.login {
  padding: 20px;
  max-width: 400px;
  margin: 0 auto;
}

.toggle-btn {
  margin-top: 15px;
  background: none;
  border: none;
  color: #007bff;
  cursor: pointer;
}

.toggle-btn:hover {
  text-decoration: underline;
}
</style>